package com.code.monitor.handler;

import com.code.monitor.model.CacheManager;
import com.code.monitor.model.ServiceInfo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleUserEventChannelHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ggh
 * @date 2023/5/8
 */
public class ReadIdleHandler extends SimpleUserEventChannelHandler<IdleStateEvent> {
    private static final Logger logger = LoggerFactory.getLogger(ReadIdleHandler.class);

    @Override
    protected void eventReceived(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        if (evt.state() != IdleState.READER_IDLE) {
            return;
        }

        ServiceInfo serviceInfo = CacheManager.getServiceInfo((SocketChannel) ctx.channel());
        logger.info("{}:长时间没有发送心跳数据，判定此机器已下线", serviceInfo.getIp());
        ctx.channel().close().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (future.isSuccess()) {
                    logger.info("{}:成功下线", serviceInfo.getIp());
                }
            }
        });
    }
}
